<template>
  <div class="gendan_edit">
    <div v-if="isAdd">新增跟单管理</div>
    <div v-else>修改跟单管理</div>
    <el-form
      ref="ruleForm"
      :model="ruleForm"
      :rules="rules"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="客户名称">
        <span
          >{{ ruleForm.customer_name }}(编号：{{ ruleForm.customer_id }})</span
        >
        <el-button type="danger" class="btn" @click="quit">重选</el-button>
      </el-form-item>
      <el-form-item label="跟单方式" prop="region1">
        <el-select v-model="ruleForm.region1">
          <el-option
            v-for="item in gendanType"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="跟单状态">
        <el-select v-model="ruleForm.region2">
          <el-option
            v-for="item in gendanStatus"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="跟单对象">
        <el-select v-model="ruleForm.region3">
          <el-option
            v-for="item in gendanObj"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="结束跟单" prop="delivery">
        <el-switch v-model="ruleForm.delivery"></el-switch>
        <el-tooltip
          class="item"
          effect="dark"
          content="结束跟单后此客户不再有跟单提醒"
          placement="top-start"
        >
          <span class="tips"></span>
        </el-tooltip>
      </el-form-item>
      <el-form-item label="下次联系" required v-if="!ruleForm.delivery">
        <el-form-item prop="date">
          <el-date-picker
            type="datetime"
            placeholder="选择日期"
            v-model="ruleForm.date"
          ></el-date-picker>
        </el-form-item>
      </el-form-item>
      <el-form-item
        label="是否提醒"
        prop="isRemind"
        style="width: 589px"
        v-if="!ruleForm.delivery"
      >
        <div class="remind" style="display: flex; align-items: center">
          <el-switch v-model="ruleForm.isRemind"></el-switch>
          <el-form-item label="提前：" style="width: 220px; margin-right: 10px">
            <el-select v-model="ruleForm.region4">
              <el-option
                v-for="item in remindTime"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <div style="width: 35px">提醒</div>
          <el-tooltip
            class="item"
            effect="dark"
            content="桌面右上角列表以及右下角浮动提醒"
            placement="top-start"
          >
            <span class="tips"></span>
          </el-tooltip>
        </div>
      </el-form-item>

      <el-form-item label="附件">
        <el-upload
          class="upload-demo"
          action="http://118.190.210.28:8080//document/addDocument"
          name="fileList"
          :on-success="uploadSuccess"
          :on-error="uploadFail"
        >
          <el-button size="small" type="primary">选择文件</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="备注">
        <el-input type="textarea" v-model="ruleForm.order_remark"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >保存</el-button
        >
        <el-button @click="quit">关闭</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapActions } from 'vuex';
import { timeFormat } from '../../utils/utils';

export default {
  name: 'EditGendan',
  data() {
    return {
      fileList: [],
      // 新增还是修改
      isAdd: true,
      fromPath: '',
      // 跟单类型
      gendanType: [
        {
          id: '1',
          label: '电话跟进',
          value: '电话跟进',
        },
        {
          id: '2',
          label: '上门拜访',
          value: '上门拜访',
        },
        {
          id: '3',
          label: 'QQ交谈',
          value: 'QQ交谈',
        },
        {
          id: '4',
          label: 'Email邮件',
          value: 'Email邮件',
        },
      ],
      // 跟单状态
      gendanStatus: [
        {
          id: '1',
          label: '等待打款',
          value: '等待打款',
        },
        {
          id: '2',
          label: '确认细节',
          value: '确认细节',
        },
        {
          id: '3',
          label: '有意向',
          value: '有意向',
        },
        {
          id: '4',
          label: '放弃跟单',
          value: '放弃跟单',
        },
        {
          id: '5',
          label: '潜在客户',
          value: '潜在客户',
        },
      ],
      // 提醒时间
      remindTime: [
        {
          id: '1',
          label: '1小时',
          value: '3600',
        },
        {
          id: '2',
          label: '2小时',
          value: '7200',
        },
        {
          id: '3',
          label: '3小时',
          value: '10800',
        },
        {
          id: '4',
          label: '1天',
          value: '86400',
        },
        {
          id: '5',
          label: '2天',
          value: '172800',
        },
        {
          id: '6',
          label: '3天',
          value: '259200',
        },
        {
          id: '7',
          label: '1周',
          value: '604800',
        },
      ],
      // 跟单对象
      gendanObj: [],
      ruleForm: {
        documentId: '',
        contact_id: '',
        customer_name: '',
        customer_id: '',
        date: '',
        delivery: false, // 结束跟单
        isRemind: true, // 是否提醒
        region1: '', // 跟单方式
        region2: '', // 跟单状态
        region3: '', // 跟单对象
        region4: '', // 提醒时间
        order_remark: '', // 备注
      },
      rules: {
        region1: [
          { required: true, message: '跟单方式不能为空', trigger: 'change' },
        ],
        date: [
          {
            type: 'date',
            required: true,
            message: '请选择时间',
            trigger: 'change',
          },
        ],
      },
    };
  },
  methods: {
    ...mapActions('gendanStore', [
      'gendanAddAction',
      'gendanUpdateAction',
      'gendanAddFileAction',
    ]),
    // 提交
    submitForm(formName) {
      if (this.isAdd) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            console.log('新增');
            this.gendanAddAction({
              contact_id: this.ruleForm.contact_id, // 跟单对象 id
              customer_id: this.ruleForm.customer_id,
              employee_name: '超级管理员',
              documentary_nextcontacttime:
                this.ruleForm.date == ''
                  ? timeFormat(Date.now())
                  : timeFormat(this.ruleForm.date.getTime()), // 下次联系时间
              documentary_remark: this.ruleForm.order_remark, // 备注
              documentary_remind: this.ruleForm.delivery == true ? 1 : 0, // 是否提示 0不提示
              documentary_status: this.ruleForm.region2, // 跟单状态
              documentary_remindtime:
                this.ruleForm.region4 == ''
                  ? timeFormat(Date.now())
                  : timeFormat(this.ruleForm.region4 * 1000 + Date.now()), // 提醒时间 + ':00.0'
              documentary_type: this.ruleForm.region1, // 跟单方式
            })
              .then((documentary_id) => {
                console.log(documentary_id);
                if (this.fileList.length) {
                  let fileArr = this.fileList.map((item) => {
                    console.log(item);
                    item.documentary_id = documentary_id;
                    item.document_name = item.fileName;
                    item.document_size = item.filesize.slice(4);
                    item.employee_name = '超级管理员';
                    item.document_url = item.fileUrl;
                    delete item.fileUrl;
                    delete item.fileName;
                    delete item.filesize;
                    delete item.fileList;
                    return item;
                  });
                  // 文件入库
                  this.gendanAddFileAction(fileArr)
                    .then(() => {
                      console.log('文件入库成功');
                    })
                    .catch((err) => {
                      console.log('文件入库失败:', err);
                    });
                }
                this.$message({
                  type: 'success',
                  message: '操作成功',
                });
                this.resetForm();
                this.$router.replace('/gendan/gendanAdd');
              })
              .catch((err) => {
                this.$message({
                  type: 'error',
                  message: '操作失败',
                });
                console.log('添加失败:', err);
              });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      } else {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            console.log('修改的数据：', this.ruleForm);
            this.gendanUpdateAction({
              documentary_id: this.ruleForm.documentId,
              contact_id: this.ruleForm.contact_id, // 跟单对象 id
              customer_id: this.ruleForm.customer_id,
              employee_name: '超级管理员',
              documentary_end: this.ruleForm.delivery == true ? 1 : 0, // 是否结束跟单 0 不结束
              documentary_nextcontacttime:
                this.ruleForm.date == ''
                  ? timeFormat(Date.now())
                  : timeFormat(this.ruleForm.date.getTime()), // 下次联系时间
              documentary_remark: this.ruleForm.order_remark, // 备注
              documentary_remind: this.ruleForm.delivery == true ? 1 : 0, // 是否提示 0不提示
              documentary_status: this.ruleForm.region2, // 跟单状态
              documentary_remindtime:
                this.ruleForm.region4 == ''
                  ? timeFormat(Date.now())
                  : timeFormat(this.ruleForm.region4 * 1000 + Date.now()), // 提醒时间 + ':00.0'
              documentary_type: this.ruleForm.region1, // 跟单方式
            })
              .then(() => {
                this.$message({
                  type: 'success',
                  message: '操作成功',
                });
              })
              .catch((err) => {
                this.$message({
                  type: 'error',
                  message: '操作失败',
                });
                console.log('修改失败:', err);
              });

            if (this.fileList.length) {
              let fileArr = this.fileList.map((item) => {
                item.documentary_id = this.$route.query.updateInfo.documentId;
                item.document_name = item.fileName;
                item.document_size = item.filesize.slice(4);
                item.employee_name = '超级管理员';
                item.document_url = item.fileUrl;
                delete item.fileUrl;
                delete item.fileName;
                delete item.filesize;
                delete item.fileList;
                return item;
              });
              // 文件入库
              this.gendanAddFileAction({
                fileList: fileArr,
              })
                .then(() => {
                  console.log('文件入库成功');
                  this.$router.replace({ path: this.fromPath });
                })
                .catch((err) => {
                  console.log('文件入库失败:', err);
                });
            }
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      }
    },

    // 退出
    quit() {
      console.log(this.$router);
      this.$router.back();
    },

    // 上传成功的回调函数
    uploadSuccess(res) {
      console.log('成功：', res.data.fileList);
      this.fileList.push(res.data.fileList[0]);
    },
    // 上传失败的回调函数
    uploadFail(err) {
      console.log('失败：', err);
    },

    // 重置
    resetForm() {
      this.ruleForm.customer_id = '';
      // this.ruleForm.date = '';
      this.ruleForm.delivery = false;
      this.ruleForm.isRemind = true;
      this.ruleForm.region2 = '';
      this.ruleForm.region3 = '';
      this.ruleForm.order_remark = '';
    },
  },

  created() {
    if (this.$route.query.editInfo) {
      this.isAdd = true;
      console.log(this.isAdd);
      const info = this.$route.query.editInfo;
      console.dir(info);
      if (info.customer_Id) {
        this.ruleForm.customer_id = info.customer_Id;
        this.ruleForm.customer_name = info.customer_name;
        this.ruleForm.customer_name = info.customer_name;
        this.ruleForm.contact_id = info.contact_id;
        let gendanInfo = {
          id: '1',
          label: info.contact_name + '-' + info.contact_phone,
          value: info.contact_id,
        };
        this.gendanObj.push(gendanInfo);
      }
    } else if (this.$route.query.updateInfo) {
      this.isAdd = false;
      let info = this.$route.query.updateInfo;
      if (info.documentId) {
        this.ruleForm.documentId = info.documentId;
        info.customerName
          ? (this.ruleForm.customer_name = info.customerName)
          : '';
        info.customer_id ? (this.ruleForm.customer_id = info.customer_id) : '';
        info.documentType ? (this.ruleForm.region1 = info.documentType) : '';
        info.documentObj
          ? (this.ruleForm.region3 =
              info.documentObj +
              (info.documentObjPhone ? info.documentObjPhone : ''))
          : '';
        info.documentTips ? (this.ruleForm.region2 = info.documentStatus) : '';
        info.remark ? (this.ruleForm.order_remark = info.remark) : '';
        info.contact_id ? (this.ruleForm.contact_id = info.contact_id) : '';
        info.documentTips === '待跟单'
          ? (this.ruleForm.delivery = false)
          : (this.ruleForm.delivery = true);
      }
    }
  },

  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.fromPath = from.path;
    });
  },
};
</script>

<style lang="scss" scoped>
.gendan_edit {
  height: 720px;
}
form {
  margin-top: 20px;
  margin-left: 200px;
}
.el-form-item {
  width: 500px;
}
.form-1 {
  width: 1000px;
}
.el-input {
  width: 200px;
}
.receiveaddress {
  width: 500px;
}

.btn {
  margin-left: 10px;
  box-sizing: border-box;
}

.tips {
  display: inline-block;
  background: url(https://demo.126e.com/theme/default/images/icon-help.png)
    no-repeat center;
  width: 20px;
  height: 36px;
  margin-left: 5px;
  vertical-align: bottom;
}
</style>